﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.InsuranceWarranty;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.CustomerService.Controllers
{
    public class InsuranceWarrantyRecordDetailController : BaseController
    {

        #region 处理任务
        public ActionResult InsuranceWarrantyRecord()
        {
            return View();
        }
        /// <summary>
        /// 获取保单信息
        /// </summary>
        /// <param name="insuranceOrderId"></param>
        /// <returns></returns>
        public ActionResult InsuranceOrderInfo(int insuranceOrderId)
        {
            var order = ServiceFactory.InsuranceOrderServiceInstance.LoadByID(insuranceOrderId);
            return View(order);
        }
        /// <summary>
        /// 获取待处理任务
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult InsuranceWarrantyRecord(InsuranceWarrantyRecordModel model)
        {
            var total = 0;
            model.InsuranceCompanyID = CurrentUser.InsuranceCompanyID;

            var list1 = (from o in ServiceFactory.InsuranceWarrantyRecordServiceInstance.GetPagingList(model, out total)
                         join a in ServiceFactory.InsuranceOrderServiceInstance.LoadEntities(t => true) on o.InsuranceOrderId equals a.ID into temp
                         from e in temp.DefaultIfEmpty()
                         join b in ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance.LoadEntities(t => true) on o.Status equals b.StatusCode into temp1
                         from f in temp1.DefaultIfEmpty()
                         select new
                         {
                             o.ID,
                             o.Reporter,
                             o.ReporterPhone,
                             StatusDesc = f.StatusName,
                             o.CreateTime,
                             LastModifyTime=o.LastModifyTime,
                             InsuranceCompany= e.InsuranceCompany,
                             e.UserName,
                             e.UserPhone,
                             e.InsuranceCompanyBranch,
                             e.ProductName,
                             e.SaleVendorName,
                             e.InsuranceCategoryName,
                             ThirdOrderNO = string.IsNullOrEmpty(e.ThirdOrderNO) ? "查看详情" : e.ThirdOrderNO
                         }).ToList();

            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list1
            }, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 处理任务详细页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Detail(int id)
        {
            var insuranceWarrantyRecord = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(id) ??
                              new InsuranceWarrantyRecord
                              {
                                  InsuranceWarrantyRecordItem = new List<InsuranceWarrantyRecordItem> { new InsuranceWarrantyRecordItem() },
                                  InsuranceWarrantyRecordFree = new List<InsuranceWarrantyRecordFree> { new InsuranceWarrantyRecordFree() }
                              };
            if (!insuranceWarrantyRecord.InsuranceWarrantyRecordItem.Any())
                insuranceWarrantyRecord.InsuranceWarrantyRecordItem = new List<InsuranceWarrantyRecordItem> { new InsuranceWarrantyRecordItem() };
            if (!insuranceWarrantyRecord.InsuranceWarrantyRecordFree.Any())
                insuranceWarrantyRecord.InsuranceWarrantyRecordFree = new List<InsuranceWarrantyRecordFree> { new InsuranceWarrantyRecordFree() };
            byte parentStatus = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance.GetParentStatusCode(insuranceWarrantyRecord.Status);
            ViewBag.ParentStatus = parentStatus;
            return View(insuranceWarrantyRecord);
        }

        #endregion
        #region 收集资料
        public ActionResult IWRDataCollect(int insuranceWarrantyRecordId)
        {
            var insuranceWarrantyRecord =
                ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(insuranceWarrantyRecordId);
            return View(insuranceWarrantyRecord);
        }
        #endregion

        #region 寄件信息
        /// <summary>
        /// 寄（寄回）修件信息
        /// </summary>
        /// <returns></returns>
        public ActionResult SendBackInfo(int id)
        {
            var order = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(id);
            //没有保存值则取默认值
            if (string.IsNullOrWhiteSpace(order.SendBackToUserName))
            {
                order.SendBackToUserName = order.InsuranceOrder.UserName;
            }
            if (string.IsNullOrWhiteSpace(order.SendBackToUserPhone))
            {
                order.SendBackToUserPhone = order.InsuranceOrder.UserPhone;
            }
            if (string.IsNullOrWhiteSpace(order.SendBackToAddress))
            {
                order.SendBackToAddress = order.D_Province.ProvinceName + order.D_City.CityName + order.AccidentAddress;
            }
            if (!order.SendBackToProvinceId.HasValue)
            {
                order.SendBackToProvinceId = order.ProvinceId;
            }
            if (!order.SendBackToCityId.HasValue)
            {
                order.SendBackToCityId = order.CityId;
            }
            return View(order);
        }
        #endregion
        #region 导出已处理案件
        [HttpPost]
        public ActionResult ExportInsuranceWarrantyRecordList(InsuranceWarrantyRecordModel model, InsuranceWarrantyRecordItemModel model1, bool IsDownloadFile, string FileName)
        {
            model.iDisplayLength = int.MaxValue;
            model.InsuranceCompanyID = CurrentUser.InsuranceCompanyID;
            var total = 0;
            var list = ServiceFactory.InsuranceWarrantyRecordServiceInstance.GetPagingList(model, out total).Include(o => o.SystemUser).Include(o => o.InsuranceOrder).AsNoTracking().ToList().Select((o, i) => new
            {
                o.ID,
                o.InsuranceOrderId,
                o.WarrantyRecordNo,
                o.Reporter,
                o.ReporterPhone,
                o.ContactName,
                o.ContactPhone,
                o.ExpectAccidentDate,
                o.ProvinceId,
                o.CityId,
                AccidentAddress = o.D_Province.ProvinceName + o.D_City.CityName + o.AccidentAddress,
                o.AccidentProsess,
                o.Remark,
                o.SystemServiceUserId,
                o.SendExpress,
                o.SendExpressNo,
                o.SendUserName,
                o.SendUserPhone,
                o.SendUserAddress,
                o.SendSignTime,
                o.SendSignUserName,
                o.RepairRemark,
                o.RepairFinishTime,
                o.SendBackExpress,
                o.SendBackExpressNo,
                o.SendBackToUserName,
                o.SendBackToUserPhone,
                o.SendBackToProvinceId,
                o.SendBackToCityId,
                o.SendBackToAddress,
                o.SendBackUserName,
                o.SendBackUserPhone,
                SendBackTime = o.SendBackTime.HasValue ? o.SendBackTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                o.Status,
                StatusDesc = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance.GetStatusName(o.Status),
                CreateTime = o.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                o.CreateBy,
                LastModifyTime = o.LastModifyTime.ToString("yyyy-MM-dd HH:mm:ss"),
                o.LastModifyBy,
                ServiceName = o.SystemUser != null ? o.SystemUser.UserDisPlayName : string.Empty,
                SendExpressPickUpTime = o.SendExpressPickUpTime.HasValue ? o.SendExpressPickUpTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                SingleTime = o.Status == 20 ? o.LastModifyTime : DateTime.MinValue,
                o.InsuranceOrder.InsuranceCompany,
                o.InsuranceOrder.InsuranceCompanyBranch,
                o.InsuranceOrder.ProductName,
                o.InsuranceOrder.ProductBrandName,
                o.InsuranceOrder.ProductModelName,
                o.InsuranceOrder.ProductTypeName,
                o.InsuranceOrder.SaleVendorName,
                o.InsuranceOrder.InsuranceCategoryName,
                o.InsuranceOrder.ThirdOrderNO,
                o.InsuranceOrder.UserName,
                o.InsuranceOrder.UserPhone,
                o.InsuranceOrder.CertificateNO,
                o.InsuranceOrder.IMEI,
                ServiceTotalAmount = o.InsuranceWarrantyRecordItem.Sum(item => item.LostNuclearPrice),
                CreateOrderTime = o.InsuranceOrder.CreateOrderTime.ToString("yyyy-MM-dd HH:mm:ss"),
                OrderNum = ++i,
            }).ToList();

            //是否需要下载资源文件， 这里是在做压缩处理
            if (IsDownloadFile && !string.IsNullOrEmpty(FileName))
            {
                //2、获取需要压缩的文件夹列表total
                string[] fileDir = new string[list.Count];
                for (int i = 0, j = fileDir.Length; i < j; i++)
                {
                    var itemList = list[i];
                    DateTime createTime = Convert.ToDateTime(itemList.CreateTime);
                    //1銆侊紙淇濆瓨璺緞蹇呴』涓?SocketChatController/CollectData涓嬬殑涓€鑷达級  骞?鏈?鏃?濮撳悕_鎵嬫満_鎶ユ鍗曞彿/绱犳潗绫诲瀷
                    string folderName = string.Format("/UploadFile/File/workOrder/{0}/{1}/{2}/{3}_{4}_{5}", createTime.Year, createTime.Month, createTime.Day, itemList.Reporter, itemList.ReporterPhone, itemList.WarrantyRecordNo);
                    fileDir[i] = Server.MapPath(folderName);
                }
                //3、异步压缩文件
                FileHelper.ZipFile(fileDir, Server.MapPath("/UploadFile/File/customerZipOrder"), FileName + ".zip");
            }

            var dt = ListToDatatableHelper.ToDataTable(list);
            dt.TableName = "List";
            List<DataTable> dataSoure = new List<DataTable> { dt };
            Dictionary<string, object> dic = new Dictionary<string, object>();
            var isProcessing = model.IsProcessing.HasValue && model.IsProcessing.Value;
            string url = isProcessing ? "InsuranceWarrantyRecordProcessingList.xlsx" : "InsuranceWarrantyRecordProcessedList.xlsx";

            string execlPath = Server.MapPath("\\").Trim('\\') + "\\ExportTemplate\\" + url;

            string fileName = isProcessing ? "跟进中的任务清单_" + DateTime.Now.ToString("yyyyMMddhhmmss") : "已处理任务清单_" + DateTime.Now.ToString("yyyyMMddhhmmss");
            ExcelHelper.ExportToExcel(execlPath, dic, dataSoure, fileName);
            return RedirectToAction("InsuranceWarrantyRecord",
                new { IsProcessing = model.IsProcessing });
        }
        #endregion
    }
}